<template>
  <div class="profile-page">
    <div class="profile-content">
      <div class="user-info">
        <h1 v-if="localStorageUser">欢迎回来{{ localStorageUser.name }}</h1>
        <button @click="logout" class="logout-btn">
          <i class="icon-logout"></i>
          安全退出
        </button>

        <p v-if="user">借阅次数/最高借阅次数：{{ user.borrowedCount + '/' + user.maxBorrow }}</p>
      </div>

      <div class="username-change">
        <h3>更改用户名</h3>
        <div class="change-container">
          <input
            v-model="newUsername"
            type="text"
            placeholder="请输入新的用户名"
            class="username-input"
          >
          <button @click="changeUsername" class="change-btn">更新用户名</button>
        </div>
      </div>

      <div class="borrowed-books">
        <h3>当前借阅</h3>
        <div class="refresh-container">
          <button @click="refreshData" class="btn-refresh">刷新</button>
        </div>
        <div v-if="borrowedBooks.length === 0" class="empty-state">
          <p>暂无借阅的图书</p>
        </div>
        <div v-else>
          <div class="book-card" v-for="book in borrowedBooks" :key="book.bookName">
            <div class="book-info">
              <div class="book-details">
                <h4>{{ book.bookName }}</h4>
                <p>借阅日期：{{ book.borrowDate }}</p>
                <p class="book-status">{{ getBookStatus(book.borrowDate) }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'ProfilePage',
  computed: {
    localStorageUser() {
      return JSON.parse(localStorage.getItem('user'));
    }
  },
  data() {
    return {
      user: {
        username: '',
        email: '',
        maxBorrow: 5,
        borrowedCount: 0
      },
      borrowedBooks: [],
      newUsername: ''
    };
  },
  methods: {
    logout() {
      localStorage.removeItem('user');
      this.$emitter.emit('user-logout');
      this.$router.push('/login');
    },
    loadUserData() {
      const storedUser = localStorage.getItem('user');
      if (storedUser) {
        const userData = JSON.parse(storedUser);
        this.user = {
          username: userData.username,
          email: userData.email,
          maxBorrow: userData.maxBorrow || 5,
          borrowedCount: userData.borrowedCount || 0
        };
      }
    },
    async refreshData() {
      try {
        const username = this.localStorageUser.name;
        const response = await axios.get(
          `http://8.134.212.44:9999/user/borrow?username=${encodeURIComponent(username)}`
        );

        if (response.data.code === 1 && response.data.data) {
          this.borrowedBooks = response.data.data.map(item => ({
            bookName: item.book_name,
            borrowDate: item.borrow_date,
            dueDate: this.calculateDueDate(item.borrow_date)
          }));
          this.user.borrowedCount = this.borrowedBooks.length;

          const updatedUser = {
            ...JSON.parse(localStorage.getItem('user')),
            borrowedCount: this.borrowedBooks.length
          };
          localStorage.setItem('user', JSON.stringify(updatedUser));
        } else {
          console.error('获取借阅数据失败:', response.data.msg);
          alert(`获取借阅数据失败: ${response.data.msg}`);
        }
      } catch (error) {
        console.error('获取借阅数据失败:', error);
        this.handleNetworkError(error);
      }
    },
    handleNetworkError(error) {
      if (error.response) {
        console.error('后端错误:', error.response.data);
        alert(`获取借阅数据失败，状态码: ${error.response.status}`);
      } else if (error.request) {
        console.error('网络请求失败:', error.request);
        alert('网络请求失败，请检查网络连接并重试');
      } else {
        console.error('请求错误:', error.message);
        alert('请求出错，请稍后重试');
      }
    },
    calculateDueDate(borrowDate) {
      const borrowDateObj = new Date(borrowDate);
      borrowDateObj.setDate(borrowDateObj.getDate() + 30);
      return borrowDateObj.toISOString();
    },
    getBookStatus(borrowDate) {
      const today = new Date();
      const borrowDateObj = new Date(borrowDate);
      const diffTime = today - borrowDateObj;
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

      if (diffDays < 7) return '新借阅';
      if (diffDays < 25) return '借阅中';
      return '即将到期';
    },
    async changeUsername() {
      if (!this.newUsername.trim()) {
        alert('请输入有效的用户名');
        return;
      }

      try {
        const email = this.localStorageUser.email;
        const response = await axios.get(
          `http://8.134.212.44:9999/user/change?email=${encodeURIComponent(email)}&new_username=${encodeURIComponent(this.newUsername)}`
        );

        if (response.data.code === 1) {
          // 更新本地存储的用户名
          const updatedUser = {
            ...JSON.parse(localStorage.getItem('user')),
            name: this.newUsername
          };
          localStorage.setItem('user', JSON.stringify(updatedUser));
          alert('用户名更新成功！');
          this.newUsername = '';
          this.loadUserData(); // 刷新用户数据
        } else {
          alert(`更新用户名失败: ${response.data.msg}`);
        }
      } catch (error) {
        console.error('更新用户名失败:', error);
        alert('更新用户名时出错，请稍后重试');
      }
    }
  },
  mounted() {
    this.loadUserData();
    this.refreshData();
  }
};
</script>

<style scoped>
.username-change {
  margin-bottom: 20px;
}

.change-container {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.username-input {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  flex: 1;
}

.change-btn {
  padding: 8px 15px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.change-btn:hover {
  background-color: #3aa373;
}
.logout-btn {
  background: #23dd96;
  color: white;
  padding: 12px 24px;
  border-radius: 8px;
  border: none;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 8px;
}

.logout-btn:hover {
  background: #2ccbd9;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(231, 76, 60, 0.3);
}




.user-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 2rem;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 2rem;
}

.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  margin-bottom: 1rem;
}

/* 借阅书籍区域 */
.borrowed-books {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 2rem;
}

.borrowed-books h3 {
  margin-bottom: 1.5rem;
  color: #2c3e50;
}

.empty-state {
  text-align: center;
  padding: 2rem;
  color: #7f8c8d;
}

.book-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  border-bottom: 1px solid #eee;
}

.book-card:last-child {
  border-bottom: none;
}

.book-info {
  display: flex;
  align-items: center;
}

.book-cover {
  width: 80px;
  height: 120px;
  margin-right: 1rem;
  object-fit: cover;
}

.book-details h4 {
  margin-top: 0;
  margin-bottom: 0.5rem;
}

.book-status {
  margin-top: 0.5rem;
  font-size: 0.9rem;
  color: #e74c3c; /* 红色表示需要注意 */
}

/* 刷新按钮区域 */
.refresh-container {
  margin-top: 2rem;
  display: flex;
  justify-content: center;
}

.btn-refresh {
  background-color: #3498db;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  cursor: pointer;
}

.btn-refresh:hover {
  background-color: #2980b9;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .book-card {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>